<template>
  <div class="app-container">
    <!-- 图片展示弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="图片预览"
      width="60%"
      center
      :before-close="handleClose"
    >
      <div class="image-preview-container">
        <img
          v-if="imageUrl"
          :src="imageUrl"
          alt="预览图片"
          class="preview-image"
          @error="handleImageError"
          @load="handleImageLoad"
        />
        <div v-else class="no-image">
          <el-icon size="48"><Picture /></el-icon>
          <p>暂无图片</p>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-overlay">
          <el-icon class="is-loading"><Loading /></el-icon>
          <p>图片加载中...</p>
        </div>
        
        <!-- 错误状态 -->
        <div v-if="error" class="error-overlay">
          <el-icon size="48"><Warning /></el-icon>
          <p>图片加载失败</p>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">关闭</el-button>
          <el-button v-if="imageUrl && !error" type="primary" @click="downloadImage">
            下载图片
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture, Loading, Warning } from '@element-plus/icons-vue'
import { getWxLoginPolling } from '@/api/wxLogin'
const route = useRoute()
const router = useRouter()
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
// 响应式数据
const dialogVisible = ref(false)
const imageUrl = ref('')
const loading = ref(false)
const error = ref(false)
const wxToken = ref(null)
const redirect = ref(undefined)
// 轮询相关
const pollingTimer = ref(null)
const maxPollingTime = 60000 // 最大轮询时间60秒
const pollingInterval = 2000 // 轮询间隔2秒
const emit =defineEmits(['handleSuccess'])
/**
 * 打开弹窗并展示图片
 * @param {string} url - 图片URL
 * @param {string} token - 微信token（可选）
 */
const open = (url, token) => {
  if (!url) {
    ElMessage.warning('请提供有效的图片链接')
    return
  }
  
  imageUrl.value = url
  dialogVisible.value = true
  loading.value = true
  error.value = false
  
  // 如果传入了token，保存起来
  if (token) {
    wxToken.value = token
  }
}

/**
 * 关闭弹窗
 */
const handleClose = () => {
  // 停止轮询
  stopPolling()
    emit('handleSuccess')
  dialogVisible.value = false
  imageUrl.value = ''
  loading.value = false
  error.value = false
  wxToken.value = null
}

/**
 * 图片加载成功
 */
const handleImageLoad = () => {
  loading.value = false
  error.value = false
  
  // 图片加载完成后，开始轮询
  if (wxToken.value) {
    startPolling()
  }
}

/**
 * 图片加载失败
 */
const handleImageError = () => {
  loading.value = false
  error.value = true
  ElMessage.error('图片加载失败，请检查图片链接是否正确')
}

/**
 * 下载图片
 */
const downloadImage = () => {
  if (!imageUrl.value) return
  
  const link = document.createElement('a')
  link.href = imageUrl.value
  link.download = getFileNameFromUrl(imageUrl.value) || 'image'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

/**
 * 从URL中提取文件名
 * @param {string} url - 图片URL
 * @returns {string} 文件名
 */
const getFileNameFromUrl = (url) => {
  try {
    const pathname = new URL(url).pathname
    return pathname.substring(pathname.lastIndexOf('/') + 1)
  } catch {
    return 'image'
  }
}

/**
 * 开始轮询检查登录状态
 */
const startPolling = () => {
  if (!wxToken.value) {
    console.warn('缺少token参数，无法轮询登录状态')
    return
  }
  
  // 清除之前的轮询
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
  }
  
  let pollingCount = 0
  const maxPollingCount = Math.floor(maxPollingTime / pollingInterval)
  
  console.log('开始轮询微信登录状态...')
  
  pollingTimer.value = setInterval(async () => {
    pollingCount++
    
    try {
      const response = await getWxLoginPolling(wxToken.value)
      
      if (response && response.code === 200) {
        if (response?.token) {
        
            // 登录成功
            stopPolling()
            handleLoginSuccess(response.token)
            return
        
        }else if(res.code ===401){
 // 二维码过期
            stopPolling()
            ElMessage.error('二维码已过期，请重新获取')
            return
        }
      } else {
        console.log('轮询响应异常:', response)
      
    }
    } catch (error) {
      console.error('检查登录状态失败:', error)
    }
    
    // 超过最大轮询次数
    if (pollingCount >= maxPollingCount) {
      stopPolling()
      ElMessage.warning('登录超时，请重新扫码')
    }
  }, pollingInterval)
}

/**
 * 停止轮询
 */
const stopPolling = () => {
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
    pollingTimer.value = null
    console.log('停止轮询')
  }
}

/**
 * 处理登录成功
 * @param {Object} loginData - 登录数据
 */
const handleLoginSuccess = (token) => {
  userStore.loginByOpenId(token).then(res=>{
 const query = route.query
        
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur]
          }
          return acc
        }, {})
        console.log(otherQueryParams,'服务号登录12')
        router.replace({ path: redirect.value || "/", query: otherQueryParams })
  })
 
  
  ElMessage.success('服务号登录成功！')

  // 关闭弹窗
  handleClose()
  
  // 可以在这里处理登录成功后的逻辑，例如：
  // 1. 保存用户信息和token
  // 2. 跳转到首页或指定页面
  // 3. 触发父组件的登录成功回调
  
  // 可以通过emit触发父组件的事件
  // emit('loginSuccess', loginData)
}

// 组件销毁时清理轮询
onUnmounted(() => {
  stopPolling()
})

// 暴露方法给父组件
defineExpose({
  open,
  handleClose,
  
})
</script>

<style scoped>
.image-preview-container {
  position: relative;
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.preview-image {
  max-width: 100%;
  max-height: 500px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  object-fit: contain;
}

.no-image {
  text-align: center;
  color: #909399;
  padding: 60px 0;
}

.no-image .el-icon {
  margin-bottom: 16px;
  color: #c0c4cc;
}

.no-image p {
  margin: 0;
  font-size: 14px;
}

.loading-overlay,
.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(245, 247, 250, 0.9);
  border-radius: 4px;
}

.loading-overlay .el-icon {
  font-size: 32px;
  color: #409eff;
  margin-bottom: 12px;
}

.loading-overlay p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.error-overlay .el-icon {
  color: #f56c6c;
  margin-bottom: 12px;
}

.error-overlay p {
  margin: 0;
  color: #f56c6c;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .image-preview-container {
    min-height: 200px;
  }
  
  .preview-image {
    max-height: 300px;
  }
}
</style>
